package zj.it.bhne.greendao;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import zj.it.bhne.greendao.entity.Students;

import static zj.it.bhne.greendao.MyApplication.getToast;
import static zj.it.bhne.greendao.MyApplication.mContext;

public class Main2Activity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "Main2Activity";
    private long  tid;
    private Button two_create;
    private List<Students> studentsList = new ArrayList<>();
    private ListView two_listView;
    private Main2Adapter mainAdapter;
    private zj.it.bhne.greendao.StudentsDao studentsDao;

    @Override
    protected void onResume() {
        super.onResume();
        studentsList = studentsDao.queryBuilder().where(zj.it.bhne.greendao.StudentsDao.Properties.Tid.eq(tid)).build().list();
        mainAdapter = new Main2Adapter(getApplicationContext(),studentsList);
        two_listView.setAdapter(mainAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Intent intent = getIntent();
        tid = intent.getLongExtra("tid",0);
        initView();

    }

    private void initView() {
        two_create =  findViewById(R.id.two_create);
        two_listView = findViewById(R.id.two_listView);
        two_create.setOnClickListener(this);
        studentsDao = MyApplication.getInstances().getDaoSession().getStudentsDao();
        two_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Students teachers = (Students) mainAdapter.getItem(position);
                getToast(mContext(),""+teachers.getId());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.two_create:
                Students students = new Students(null,tid,"朱江",18);
                long num = studentsDao.insert(students);
                if (num>0){
                    getToast(mContext(),"创建成功");
                    studentsList = studentsDao.queryBuilder().where(zj.it.bhne.greendao.StudentsDao.Properties.Tid.eq(tid)).build().list();
                    mainAdapter = new Main2Adapter(getApplicationContext(),studentsList);
                    two_listView.setAdapter(mainAdapter);
                }
                break;
        }
    }
}
